<?php
namespace app\api\task;


use app\admin\model\Roomclean;
use app\admin\model\Shoporder;
use app\admin\model\Shoproom;
use app\admin\model\Shoproombook;
use app\admin\model\Userplan;
use app\admin\model\Userplanitem;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Log;

class WorkTask extends Command
{

    protected  $serv;

    protected function configure()
    {
        $this->setName('task')
            ->setDescription('task');
    }


    protected function execute(Input $input, Output $output)
    {
        $this->serv = new \swoole_server("0.0.0.0",10000);
        $this->serv->set([
            'task_worker_num' => 100
        ]);
        $this->serv->on("WorkerStart",function ($serv,$woker_id){
            if ($woker_id == 0){
                //每隔1000ms触发一次
                swoole_timer_tick(4000, function ($timer_id) {

                    Log::info("=====time=====".date("Y-m-d H:i:s",time()));



                    $shopOrderModel = new Shoporder();


                    $time = strtotime("-3 minutes",time());
                    $bookOrderBookModel = new Shoproombook();
                    $list = $shopOrderModel->where('book_end',"<",$time)->where('status','in',['doing','payed'])->select();

                    $shopRoom = new Shoproom();
                    foreach ($list as $key=>$val){
                        $shopOrderModel->where('id',$val['id'])->update(['status'=>'done']);

                        //修改包厢为待保洁状态，将包厢改成空闲中
                        $shopRoom->where('id',$val['room_id'])->update(['is_clean'=>-1,'status'=>'free']);

                    }



                    $list = $bookOrderBookModel->where('end_time',"<",$time)->where('status','undo')->select();
                    foreach ($list as $key=>$val){
                        $bookOrderBookModel->where('id',$val['id'])->update(['status'=>'done']);
                    }



//                    $time = strtotime("+12 hours",time());
//
//
//                    $cleanRoomModel = new Roomclean();
//                    $list = $cleanRoomModel->where('status','undo')->where("end_time",">=",$time)->select();
//
//                    for($i =0;$i<count($list);$i++){
//
//                        $this->serv->task(json_encode($list[$i]));
//                    }
                });
            }
        });

        $this->serv->on("receive",function ($serv,$fd,$from_id,$data){
            $serv->send($fd,"Server:".$data);
        });

        $this->serv->on("task",function ($serv,$fd,$from_id,$data){

            $cleanRoomModel = new Roomclean();

            $obj = json_decode($data,true);
            $cleanRoomModel->where('id',$obj['id'])->update(['status'=>'undone']);

        });



        $this->serv->start();
    }





}